package lotteryGui;


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import lotteryModel.Tickets;
import lotteryModel.Users;


@SuppressWarnings("serial")
public class Interphase extends JFrame {
    private JFrame f;
    private JMenu jMenu1;
    private JMenu jMenu2;
    private JMenu jMenu3;
    private JMenuBar jMenuBar1;
    private JMenuItem jMenuItem1;
    private JMenuItem jMenuItem2;
    private JMenuItem jMenuItem3;
    private JPanel jPanel1;
    private Users user;
    private JButton jButton1;
    private JButton jButton2;

    private JButton jButton5;
    private JButton jButton3;
    private JButton jButton4;

    public JFrame getF() {
        return f;
    }

    public void setF(JFrame f) {
        this.f = f;
    }

    public Interphase(Users user) {
        super();
        this.user = user;
        initComponents();
    }

    private void initComponents() {
        f=new JFrame("彩票系统");
        f.setSize(893,555);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setResizable(false);
        f.setLocationRelativeTo(null) ;
        f.setLayout(new BorderLayout());
        jPanel1 = new JPanel(new FlowLayout());
        jMenuBar1 = new JMenuBar();
        jMenu1 = new JMenu();
        jMenuItem1 = new JMenuItem();
        jMenu2 = new JMenu();
        jMenuItem2 = new JMenuItem();
        jMenu3 = new JMenu();
        jMenuItem3 = new JMenuItem();

        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //jPanel1.setSize(893,555);
        jPanel1.setBounds(0, 0, 893, 555);
        String filePath = System.getProperty("user.dir");  //获得当前程序路径
        String fileName = filePath+"/image/picture.jpg";
        ImageIcon image = new ImageIcon(fileName);
        image.setImage(image.getImage().getScaledInstance(893, 555,Image.SCALE_DEFAULT ));
        JLabel label = new JLabel(image);
        jPanel1.add(label);

        jMenu1.setText("购买彩票");

        jMenuItem1.setText("36选7");
        jMenuItem1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });

        jMenuItem2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });

        jMenuItem3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });

        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("往期记录");

        jMenuItem2.setText("往期记录");

        jMenu2.add(jMenuItem2);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("购买记录");

        jMenuItem3.setText("购买记录");
        jMenu3.add(jMenuItem3);

        jMenuBar1.add(jMenu3);

        f.setJMenuBar(jMenuBar1);

        f.setContentPane(jPanel1);
        f.setVisible(true);


        f.pack();
    }


    private void jMenuItem1ActionPerformed(ActionEvent evt) {
        // TODO add your handling code here:
        jButton1 = new JButton("随机摇号");
        jButton2 = new JButton("一键清空");

        jButton5 = new JButton("确认");
        jButton3 = new JButton("购买");
        jButton4 = new JButton("删除");

        TextField t1 = new TextField();
        TextField t2 = new TextField();
        TextField t3 = new TextField();
        TextField t4 = new TextField();
        TextField t5 = new TextField();
        TextField t6 = new TextField();
        TextField t7 = new TextField();
        TextField t8 = new TextField();
        t1.setFont(new Font("Dialog", 0, 18));
        t2.setFont(new Font("Dialog", 0, 18));
        t3.setFont(new Font("Dialog", 0, 18));
        t4.setFont(new Font("Dialog", 0, 18));
        t5.setFont(new Font("Dialog", 0, 18));
        t6.setFont(new Font("Dialog", 0, 18));
        t7.setFont(new Font("Dialog", 0, 18));
        t8.setFont(new Font("Dialog", 0, 18));
        jPanel1.removeAll();
        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);



        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(59, 59, 59)
                                .addComponent(t1, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(t2, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(t3, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(t4, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(t5, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(t6, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(t7, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
                                .addGap(77, 77, 77)
                                .addComponent(t8, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jButton4, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButton3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButton2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButton1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addComponent(jButton5, GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                                .addGap(99, 99, 99))
        );


        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(78, 78, 78)
                                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                        .addComponent(jButton1)
                                        .addComponent(jButton5)
                                        .addComponent(t7, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE)
                                        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                                .addComponent(t5, GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                                                .addComponent(t4, GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                                                .addComponent(t3, GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                                                .addComponent(t2, GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                                                .addComponent(t1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(t6, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addComponent(t8, GroupLayout.DEFAULT_SIZE, 22, GroupLayout.DEFAULT_SIZE))

                                .addGap(34, 34, 34)

                                .addComponent(jButton2)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 211, Short.MAX_VALUE)

                                .addComponent(jButton3)
                                .addGap(40, 40, 40)

                                .addComponent(jButton4)
                                .addContainerGap(196, Short.MAX_VALUE))
        );



        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(70,200,600, 300);
        jPanel1.add(scrollPane);

        JTable table = new JTable();

        DefaultTableModel dtm = new DefaultTableModel(
                new Object[][] {  },
                new String[] { "日期","号码", "倍数" });

        table.setModel(dtm);

        table.setBounds(100, 100, 200, 200);


        scrollPane.setPreferredSize(new Dimension(500, 400));

        scrollPane.setAutoscrolls(true);
        scrollPane.setViewportView(table);




        jButton1.addActionListener((ActionEvent e)->{
            String balls[] = getrandom();
            t1.setText(balls[0]);
            t2.setText(balls[1]);
            t3.setText(balls[2]);
            t4.setText(balls[3]);
            t5.setText(balls[4]);
            t6.setText(balls[5]);
            t7.setText(balls[6]);
        });


        jButton5.addActionListener((ActionEvent a)->{
            Date myDate = new Date();
            String balls[] = {t1.getText(),t2.getText(),t3.getText(),t4.getText(),t5.getText(),t6.getText(),t7.getText()};

            if(t1.getText().equals("")||t2.getText().equals("")||t3.getText().equals("")||t4.getText().equals("")||t5.getText().equals("")||t6.getText().equals("")||t7.getText().equals("")||t8.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "请重新输入", "内容不能为空", JOptionPane.ERROR_MESSAGE);
            }

            else {
                @SuppressWarnings("deprecation")
                Tickets ticket1 = new Tickets(myDate.toLocaleString(),user.getId(),balls,t8.getText(),"NoAward");
                dtm.addRow(new String[]{ticket1.getDate(),ticket1.toString(),ticket1.getTimes()});
            }

        });

        jButton4.addActionListener((ActionEvent a)->{
            int selectedRow = table.getSelectedRow();
            if(selectedRow!=-1) dtm.removeRow(selectedRow);
        });

        jButton2.addActionListener((ActionEvent e)->{
            t1.getText(); t1.setText("");
            t2.getText(); t2.setText("");
            t3.getText(); t3.setText("");
            t4.getText(); t4.setText("");
            t5.getText(); t5.setText("");
            t6.getText(); t6.setText("");
            t7.getText(); t7.setText("");
            t8.getText(); t8.setText("");
        });

        jButton3.addActionListener((ActionEvent e)->{
            try {
                int selectedRow = table.getSelectedRow();
                Date myDate = new Date();
                if(selectedRow!=-1) {
                    Object value1 = dtm.getValueAt(selectedRow,1);
                    Object value2 = dtm.getValueAt(selectedRow,2);
                    if(user.getBalance()<=Integer.parseInt(String.valueOf(value2))*2) {
                        String filePath = System.getProperty("user.dir");  //获得当前程序路径
                        String fileName = filePath+"/Record.txt";
                        File fp = new File(fileName);
                        FileOutputStream fos = null;
                        fos = new FileOutputStream(fp,true);
                        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
                        @SuppressWarnings("deprecation")
                        String str = myDate.toLocaleString()+" "+String.valueOf(value1)+" "+String.valueOf(value2)+ " "+"NoAward"+" "+user.getId();
                        osw.write(str);
                        osw.write("\r\n");
                        osw.close();
                        dtm.removeRow(selectedRow);
                        Cost(value2);
                    }
                    else JOptionPane.showMessageDialog(null, "余额不足", null, JOptionPane.ERROR_MESSAGE);
                }

            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                System.out.println(e1);
                e1.printStackTrace();
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                System.out.println(e1);
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                System.out.println(e1);
                e1.printStackTrace();
            }
        });
    }


    private void jMenuItem2ActionPerformed(ActionEvent evt) {
        jPanel1.removeAll();
        @SuppressWarnings("unused")
        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);

        JScrollPane scrollPane1 = new JScrollPane();
        scrollPane1.setBounds(80,25, 700, 500);
        jPanel1.add(scrollPane1);

        JTable table1 = new JTable();

        DefaultTableModel dtm1 = new DefaultTableModel(
                new Object[][] {  },
                new String[] { "日期","号码", "奖池" ,"特等奖","一等奖"});

        table1.setModel(dtm1);

        table1.setBounds(100, 100, 200, 200);


        scrollPane1.setPreferredSize(new Dimension(700, 554));

        scrollPane1.setAutoscrolls(true);
        scrollPane1.setViewportView(table1);
        FileReader record;
        try {
            String filePath = System.getProperty("user.dir");  //获得当前程序路径
            String fileName = filePath+"/History.txt";
            record = new FileReader(fileName);
            BufferedReader bf = new BufferedReader(record);
            String str;
            while((str=bf.readLine())!=null) {
                String[] strs = str.split(" ");
                dtm1.addRow(new String[] {strs[0]+" "+strs[1],strs[2],strs[3],strs[4],strs[5]});
            }
            bf.close();
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    private void jMenuItem3ActionPerformed(ActionEvent evt) {
        jPanel1.removeAll();

        @SuppressWarnings("unused")
        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);

        JScrollPane scrollPane1 = new JScrollPane();
        scrollPane1.setBounds(80,25, 700, 500);
        jPanel1.add(scrollPane1);

        JTable table1 = new JTable();

        DefaultTableModel dtm1 = new DefaultTableModel(
                new Object[][] {  },
                new String[] { "日期","号码", "倍数" ,"状态"});

        table1.setModel(dtm1);

        table1.setBounds(100, 100, 200, 200);


        scrollPane1.setPreferredSize(new Dimension(800, 553));

        scrollPane1.setAutoscrolls(true);
        scrollPane1.setViewportView(table1);
        FileReader record;
        try {
            String filePath = System.getProperty("user.dir");  //获得当前程序路径
            String fileName = filePath+"/Record.txt";
            record = new FileReader(fileName);
            BufferedReader bf = new BufferedReader(record);
            String str;
            while((str=bf.readLine())!=null) {
                String[] strs = str.split(" ");
                if(user.getId().equals(strs[5])) dtm1.addRow(new String[] {strs[0]+" "+strs[1],strs[2],strs[3],strs[4]});
            }
            bf.close();
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public String[] getrandom() {
        String []pool = {
                "1","2","3","4","5","6","7","8",
                "9","10","11","12","13","14","15","16",
                "17","18","19","20","21","22","23","24",
                "25","26","27","28","29","30","31","32",
                "33","34","35","36"
        };

        String[] balls = new String[7];
        int length = 0 ;


        boolean[] used = new boolean[pool.length];
        Random r = new Random();
        while(true){
            int index = r.nextInt(pool.length);

            if(used[index])
                continue ;
            balls[length++] = pool[index];
            used[index] = true ;
            if(length == balls.length)
                break ;
        }
        int balls1[] = new int[balls.length];
        int i = 0;
        for(String s:balls) {
            balls1[i++] = Integer.parseInt(s);
        }
        i=0;
        Arrays.sort(balls1);
        for(int s:balls1) {
            balls[i++] = String.valueOf(s);
        }
        return balls;
    }


    public void Cost(Object value) {
        BufferedReader record = null;
        PrintWriter record1 = null;
        ArrayList<Users> us = new ArrayList<>();
        try {
            String filePath = System.getProperty("user.dir");  //获得当前程序路径
            String fileName = filePath+"/Users.txt";
            record = new BufferedReader(new FileReader(fileName));

            String str;
            int money = 0;
            while(( str = record.readLine())!=null) {
                String[] strs = str.split(" ");
                if(strs[0].equals(user.getId())) {
                    money = Integer.parseInt(strs[3])-Integer.parseInt(String.valueOf(value))*2;
                }
                Users temp = new Users(strs[0],strs[1],strs[2],money,strs[4]);
                //System.out.println(strs[0]+strs[1]+strs[2]+money+strs[4]);
                //System.out.println(temp.getId()+" "+temp.getUsername()+" "+temp.getPassword()+" "+temp.getBalance()+" "+temp.getPhone());
                us.add(temp);
            }
            String filePath1 = System.getProperty("user.dir");  //获得当前程序路径
            String fileName1 = filePath1+"/Users.txt";
            record1 = new PrintWriter(new BufferedWriter(new FileWriter(fileName1)));
            for(Users s:us) {
                //System.out.println(s.getId()+" "+s.getUsername()+" "+s.getPassword()+" "+s.getBalance()+" "+s.getPhone());
                record1.println(s.getId()+" "+s.getUsername()+" "+s.getPassword()+" "+s.getBalance()+" "+s.getPhone());

            }
            record.close();
            record1.close();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}